package com.coldworks.coldjoke.task;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.coldworks.base.manager.BaseNetworkManager;
import com.coldworks.coldjoke.manager.UserManager;
import com.coldworks.coldjoke.model.ReplyModel;
import com.coldworks.coldjoke.model.UserModel;
import com.coldworks.coldjoke.ui.JokePageCell;
import com.coldworks.coldjoke.util.CONST;
import com.coldworks.coldjoke.util.NetworkUtil;

public class JokeReplyTask extends AsyncTask<Void, Void, String> {
	protected final Logger log = LoggerFactory.getLogger(this.getClass());
	private Context context;
	private String replyContent;
	private String jokeId;
	private JokePageCell cellPlaying;

	public JokeReplyTask(Context context, String pReplyContent,
			JokePageCell pCellPlaying) {
		this.context = context;
		this.replyContent = pReplyContent;
		this.cellPlaying = pCellPlaying;
		this.jokeId = cellPlaying.getJokeModel().getJokeId();
	}

	@Override
	protected String doInBackground(Void... params) {
		List<NameValuePair> param = new ArrayList<NameValuePair>();
		param.add(new BasicNameValuePair("action", "post_comment"));
		param.add(new BasicNameValuePair("joke_id", jokeId));
		param.add(new BasicNameValuePair("content", replyContent));

		String url = CONST.URL.COMENT;
		HttpPost httpPost = new HttpPost(url);
		HttpParams httpParams = new BasicHttpParams();
		try {
			String sessionId = UserManager.getInstance().getSessionId();
			HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
			httpPost.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8));
			httpPost.setHeader("Cookie", "webpy_session_id=" + sessionId);
			HttpResponse response = BaseNetworkManager.getInstance()
					.createHttpClient(context).execute(httpPost);
			if (isCancelled()) {
				log.info("cancelled");
				return "已经取消发表";
			}
			if (response.getStatusLine().getStatusCode() == 200) {
				Header contentEncoding = response
						.getFirstHeader("Content-Encoding");
				JSONObject jsonObject = null;
				if (contentEncoding != null
						&& contentEncoding.getValue().equalsIgnoreCase("gzip")) {
					jsonObject = NetworkUtil.getInstance().getJsonObjectByGzip(
							response.getEntity().getContent());
				} else {
					jsonObject = NetworkUtil.getInstance().getJSONObject(
							response.getEntity().getContent());
				}
				if (jsonObject == null) {
					return "服务器开小差了，请稍后再试";
				}
				if (jsonObject.getString("success").equals("true")) {
					UserModel userInfo = new UserModel();
					userInfo.setUserIcon(jsonObject
							.getString("author_cover_url"));
					userInfo.setUserId(jsonObject.getString("author_user_id"));
					userInfo.setUserName(jsonObject
							.getString("author_user_name"));
					return null;
				} else {
					String res = jsonObject.getString("error");
					return res;
				}
			} else {
				log.info(String.valueOf(response.getStatusLine()
						.getStatusCode()));
				return "服务器开小差了，请稍后再试";
			}
		} catch (ClientProtocolException e) {
			log.error("", e);
		} catch (IOException e) {
			log.error("", e);
		} catch (JSONException e) {
			log.error("", e);
		}
		return "网络异常，请稍后再试";
	}

	@Override
	protected void onPostExecute(String res) {
		super.onPostExecute(res);
		if (res == null) {
			// 发表成功
			Toast.makeText(context, "评论发表成功", Toast.LENGTH_SHORT).show();
			if (jokeId != cellPlaying.getJokeModel().getJokeId()) {
				return;
			}
			ReplyModel replyModel = new ReplyModel();
			replyModel.setUserName(UserManager.getInstance().getUserName());
			replyModel.setReplyContent(replyContent);
			cellPlaying.setReplyNew(replyModel);
		} else {
			// 发表失败,res是原因
			Toast.makeText(context, res, Toast.LENGTH_SHORT).show();
		}
	}

}
